<template>
  <div class="app-container search-class">
    <el-row style="margin-bottom:10px">
      <span style="margin-right:20px;">{{ title_data }}</span>
      <el-input v-model.number="total_row_num" placeholder="Quantity" style="width: 100px" @oninput="value=value.replace(/^\d+$|^\d+[.]?\d+$/,'')" />
      <el-button type="primary" icon="el-icon-download" circle @click="selectPage" />
      <!-- <el-link icon="el-icon-download" href="http://work.dcloud.yunku.live/api/user/order/index?download=1.html" type="primary">Download</el-link> -->
    </el-row>
    <el-table
      :data="rolesList"
      style="width: 100%;margin-top:30px;"
      :cell-style="cellChangeColor"
      :empty-text="empty_text"
      border
    >
      <el-table-column align="center" prop="id" label="ID" width="50">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="Title" width="150">
        <template slot-scope="scope">{{ scope.row.title }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Rooms & Others">
        <template slot-scope="scope">{{ scope.row.desc }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Client" width="150">
        <template slot-scope="scope">{{ scope.row.hotel_name }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Work Instruction">
        <template slot-scope="scope">{{ scope.row.wi_names.replace(/\,/g, '\n') }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Due date" width="180">
        <template slot-scope="scope">{{ scope.row.due_date }}</template>
      </el-table-column>
      <el-table-column align="header-center" label="Status" width="100">
        <template slot-scope="scope">{{ scope.row.status_name }}</template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="80">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="8">
              <el-link class="el-icon-document icon-class" @click="openorderdetailsComp(scope)" />
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :visible.sync="dialogVisible_per"
      title="Download"
      width="500px"
    >
      <div>
        <el-row style="margin-bottom:20px;margin-top: -10px;padding-left: 20px">
          <el-col v-for="item in total_row_total" :key="item" :span="6" style="margin-bottom:10px">
            <el-link type="primary" @click="downloadWorkOrder(item)">Page {{ item }}</el-link>
          </el-col>
        </el-row>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible_per = false">Cancel</el-button>
      </div>
    </el-dialog>
    <el-pagination
      style="margin-top:10px;float:right"
      background
      layout="slot,prev,pager,next"
      :total="totalpage"
      :current-page="search.page"
      :page-size="search.per_page"
      @current-change="handleIndexChange"
    >
      <span class="el-pagination__total">Total {{ totalpage }}</span>
    </el-pagination>
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
import {
  getorderinfo,
  getdictionary
} from '@/api/order/index'
import { parseTime } from '@/utils'
import { getToken } from '@/utils/auth' // get token from cookie

export default {
  components: {
    // MyTest
  },
  data() {
    return {
      total_row_num: 50,
      total_row_total: undefined,
      dialogVisible_per: false,
      createShow: false,
      editShow: false,
      orderinfo: {
        id: '',
        title: '',
        desc: '',
        priority: 2,
        hotel_id: '',
        hotel_contact_ids: [],
        wi_ids: [],
        notes: [],
        staffs: [],
        due_date: ''
      },
      search: {
        time_start: '',
        time_end: '',
        hotel_id: '',
        keyword: '',
        page: 1,
        request_type: '',
        order_search_id: 1,
        per_page: 10
      },
      notesText: '',
      notes: [{
        note: ''
      }],
      empty_text: '',
      prioritylist: [],
      hotellist: [],
      hotecontectllist: [],
      hotecontectlids: '',
      wilist: [],
      wiids: [],
      staffslist: [],
      staffsids: [],
      totalpage: 0,
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      title_data: '',
      tokenData: '',
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        title: [{ required: true, message: 'Please enter a title', trigger: 'blur'
        }],
        desc: [{ required: true, message: 'Please Enter Description', trigger: 'blur'
        }],
        priority: [{ required: true, message: 'Please Choose Priority', trigger: 'change'
        }],
        hotel_id: [{ required: true, message: 'Please Choose Hotel', trigger: 'change'
        }]
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    if (this.$route.query && this.$route.query.order_search_id) {
      // 业务逻辑
      this.search.order_search_id = this.$route.query.order_search_id
    }
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
    this.conRouter()
    this.conToken()
  },
  methods: {
    cellChangeColor({ row, column, rowIndex, columnIndex }) {
      if (row.status === 2 && columnIndex === 6) { return { backgroundColor: '#9267be', color: 'white' } }
      if (row.status === 3 && columnIndex === 6) { return { backgroundColor: '#6ed3d0' } }
      return ''
    },
    status_change(scope) {
      if (scope.row.status === 1) {
        return 'table-info-row1'
      } else if (scope.row.status === 2) {
        return 'table-info-row2'
      } else if (scope.row.status === 3) {
        return 'table-info-row3'
      }
    },
    handleIndexChange(index) {
      this.search.page = index
      this.getRoles()
    },
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async conRouter() {
      const { roles, role_infos } = await this.$store.dispatch('user/getInfo')
      if (roles.some(p => p === '1')) {
        this.createShow = true
        this.editShow = true
      } else {
        const res = role_infos[0].routes
        this.createShow = res.some(p => p === '/order/add')
        this.editShow = res.some(p => p === '/order/edit')
      }
    },
    openorderdetailsComp(scope) {
      this.$router.push({
        path: '/order/orderdetails',
        query: { id: scope.row.id }
      })
    },
    async conToken() {
      this.tokenData = getToken()
    },
    gettableinto() {
      this.keyword = this.keywords
      this.getRoles()
    },
    async getRoles() {
      this.empty_text = 'Loading ......'
      await getorderinfo(this.search).then(res => {
        this.rolesList = res.data
        this.totalpage = res.total
        this.title_data = res.title
        this.per_page = res.per_page
        this.current_page = res.current_page
        this.empty_text = 'Can\'t find record in table'
      }).catch(() => {
        this.rolesList = []
        this.empty_text = 'Can\'t find record in table'
      })
      await this.gethotelinfo()
    },
    async getpriorityinfo() {
      this.prioritylist = await getdictionary({ dict_type: 'priority' })
    },
    async gethotelinfo() {
      this.hotellist = await getdictionary({ dict_type: 'hotel' })
    },
    async gethotelcontectinfo(val) {
      this.hotecontectllist = await getdictionary({ dict_type: 'hotel_contact', hotel_id: val })
      this.hotecontectlids = ''
      this.wiids = []
      this.getwiinfo(val)
    },
    async getwiinfo(val) {
      this.wilist = await getdictionary({ dict_type: 'wi', hotel_id: val })
    },
    async getstaffsinfo(val) {
      this.staffslist = await getdictionary({ dict_type: 'staff' })
    },
    async selectPage() {
      if (!this.total_row_num || this.total_row_num <= 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the quantity per page!'
        })
        return
      } else {
        const per_search = Object.assign({}, this.search)
        per_search.request_type = 'download_query'

        await getorderinfo(per_search).then(async response => {
          if (response.total > 0) {
            if (response.total <= this.total_row_num) {
              // 直接下载
              return this.downloadWorkOrder(1)
            }
            this.total_row_total = Math.ceil(response.total / this.total_row_num)
            this.dialogVisible_per = true
          } else {
            this.$message({
              type: 'warning',
              message: 'Can\'t find record to download!'
            })
          }
        })
      }
    },
    async downloadWorkOrder(value) {
      this.downloadSearch = Object.assign({}, this.search)
      this.downloadSearch.download = 1
      if (this.downloadSearch.time_start) {
        this.downloadSearch.time_start = parseTime(this.downloadSearch.time_start, '{y}-{m}-{d}')
      }
      if (this.downloadSearch.time_end) {
        this.downloadSearch.time_end = parseTime(this.downloadSearch.time_end, '{y}-{m}-{d}')
      }
      const url = 'user/order/index?keyword=' + this.downloadSearch.keyword + '&page=' + value + '&per_page=' + this.total_row_num + '&hotel_id=' + this.downloadSearch.hotel_id +
      '&time_start=' + this.downloadSearch.time_start + '&time_end=' + this.downloadSearch.time_end + '&request_type=download&token=' + this.tokenData
      console.log(url)
      window.open(process.env.VUE_APP_BASE_API + url)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .icon-class {
    font-size: 20px;
  }
}
</style>

<style>
.table-info-row1 td {
      color: #03be1cef;
 }
.table-info-row2 td {
      color: #0057facb;
 }
.table-info-row3 td {
      color: #fd0000c5;
 }
.search-class .el-table .cell {
  white-space: pre-line !important;
}
</style>
